package cn.com.joycode.nimble.core.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class NetUtil {

    public static void disableSslVerification() {
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
            sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    if (ObjectUtil.isNull(arg0)) {
                        throw new CertificateException();
                    }
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    if (ObjectUtil.isNull(arg0)) {
                        throw new CertificateException();
                    }
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            HostnameVerifier allHostsValid = (String hostname, SSLSession session) -> {
                if (StrUtil.isNotBlank(hostname)) {
                    return true;
                } else {
                    return false;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            log.error("处理ssl证书异常", e);
        }
    }
}
